package com.ship.boats.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ship.boats.domain.OilinessPrice;
import com.ship.boats.domain.dto.CreateOilinessPriceRq;
import com.ship.boats.domain.dto.CurveDataRq;
import com.ship.boats.domain.dto.ExportOilinessPriceRq;
import com.ship.boats.domain.dto.QueryOilinessPriceRq;
import com.ship.boats.domain.vo.ExportOilinessPriceInfo;
import com.ship.boats.domain.vo.QueryForwardOilinessInfo;
import com.ship.boats.domain.vo.QueryOilinessPriceInfo;
import com.ship.boats.mapper.OilinessPriceMapper;
import com.ship.boats.service.OilinessPriceService;
import com.ship.common.core.base.Page;
import com.ship.common.core.exception.ServiceException;
import com.ship.common.core.utils.BeanCopyUtils;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.security.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <b>OilinessPriceServiceImpl</b>
 *
 * @description: OilinessPriceServiceImpl <br>
 * @date: 2024/3/19 09:08 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class OilinessPriceServiceImpl implements OilinessPriceService {
    private static final Logger logger = LoggerFactory.getLogger(OilinessPriceServiceImpl.class);

    @Autowired
    private OilinessPriceMapper oilinessPriceMapper;

    @Override
    public boolean createOilinessPrice(CreateOilinessPriceRq rq) {
        OilinessPrice oilinessPrice = new OilinessPrice();
        BeanCopyUtils.copy(rq,oilinessPrice);
        oilinessPrice.setDataSource("期现一体化");
        oilinessPrice.setCreateUser(SecurityUtils.getUsername());
        oilinessPrice.setCreateTime(new Date());
        oilinessPrice.setUpdateUser(SecurityUtils.getUsername());
        oilinessPrice.setUpdateTime(new Date());
        oilinessPrice.setEnable("1");
        oilinessPriceMapper.insert(oilinessPrice);
        return false;
    }

    @Override
    public PageInfo<QueryOilinessPriceInfo> queryPage(QueryOilinessPriceRq rq) {
        PageHelper.startPage(rq.getPageNum(),rq.getPageSize());
        String curveName = null;
        List<String> queryList = null;
        if (CollectionUtil.isNotEmpty(rq.getCurveNameList())){
            if (rq.getCurveNameList().size() == 1){
                curveName = rq.getCurveNameList().get(0);
            }else {
                queryList = rq.getCurveNameList();
            }
        }
        String settleFwd = "S";
        List<QueryOilinessPriceInfo> oilinessPriceList = oilinessPriceMapper.queryOilinessList(curveName,settleFwd,queryList,rq.getStartTime(),rq.getEndTime(),null);
        logger.info("查询油气价格返回结果:{}"+ JSONUtil.parse(oilinessPriceList));
        PageInfo<QueryOilinessPriceInfo> pageInfo = new PageInfo<>(oilinessPriceList);
        return pageInfo;
    }

    @Override
    public List<String> queryOilinessNameList(String settleFwd) {
        List<String> oilinessNameList = oilinessPriceMapper.queryOilinessName(settleFwd);
        return oilinessNameList.stream().distinct().collect(Collectors.toList());
    }

    @Override
    public boolean createCashForwardData(CurveDataRq curveData) {
        OilinessPrice oilinessPrice = new OilinessPrice();
        oilinessPrice.setCurveUid(curveData.getCurveUID());
        oilinessPrice.setCurveName(curveData.getCurveName());
        DateTime curveDate = DateUtil.parse(curveData.getCurveDate(), DatePattern.NORM_DATETIME_FORMATTER);
        oilinessPrice.setCurveDate(curveDate);
        oilinessPrice.setCurrency(curveData.getCurrency());
        oilinessPrice.setValue(curveData.getValue());
        oilinessPrice.setOilinessUnit(curveData.getCurrency() + "/" + curveData.getUom());
        oilinessPrice.setPeriodicity(curveData.getPeriodicity());
        oilinessPrice.setSettleFwd(curveData.getSettleFwd());
        oilinessPrice.setRangeSeq(curveData.getRangeSEQ());
        //计算涨幅
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(curveDate);
        calendar.add(Calendar.DATE, -1);
        Date yesterday = calendar.getTime();
        String queryDate = DateUtil.format(yesterday, DatePattern.NORM_DATE_FORMATTER);
        //查询前一天油气价格
        if ("S".equals(curveData.getSettleFwd())) {
            List<OilinessPrice> priceList = oilinessPriceMapper.queryOilinessPriceByName(curveData.getCurveUID(), queryDate,null);
            if (CollectionUtil.isNotEmpty(priceList) && priceList.get(0).getValue() != 0) {
                BigDecimal bg = new BigDecimal(((curveData.getValue() - priceList.get(0).getValue()) / priceList.get(0).getValue()) * 100);
                double rangeFluctuation = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                oilinessPrice.setRangeFluctuation(rangeFluctuation + "%");
            }
        }
        calendar.setTime(DateUtil.parse(curveData.getCurveDate(), DatePattern.NORM_DATE_FORMAT));
        oilinessPrice.setRangeBegDate(DateUtil.parse(curveData.getRangeBegDate(), DatePattern.NORM_DATETIME_FORMATTER));
        oilinessPrice.setRangeEndDate(DateUtil.parse(curveData.getRangeEndDate(), DatePattern.NORM_DATETIME_FORMATTER));
        oilinessPrice.setDataSource("期现一体化");
        oilinessPrice.setEnable("1");
        //校验数据是否已存在
        String format = DateUtil.format(DateUtil.parse(curveData.getCurveDate(), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATE_FORMAT);
        List<OilinessPrice> oilinessPriceList = oilinessPriceMapper.queryOilinessPriceByName(curveData.getCurveUID(),null,curveData.getSettleFwd());
        boolean status = false;
        if (CollectionUtil.isNotEmpty(oilinessPriceList)){
            if ("F".equals(curveData.getSettleFwd())){
                boolean b = oilinessPriceList.stream().anyMatch(item -> item.getRangeBegDate().getTime() == DateUtil.parse(curveData.getRangeBegDate(), DatePattern.NORM_DATETIME_FORMATTER).getTime());
                if (oilinessPriceList.stream().anyMatch(item -> item.getRangeBegDate().getTime() == DateUtil.parse(curveData.getRangeBegDate(),DatePattern.NORM_DATETIME_FORMATTER).getTime()) &&
                        oilinessPriceList.stream().anyMatch(item -> item.getRangeEndDate().getTime() == DateUtil.parse(curveData.getRangeEndDate(),DatePattern.NORM_DATETIME_FORMATTER).getTime())){
                    Optional<OilinessPrice> first = oilinessPriceList.stream().filter(item -> item.getRangeEndDate().getTime() == DateUtil.parse(curveData.getRangeEndDate(), DatePattern.NORM_DATETIME_FORMATTER).getTime()).findFirst();
                    oilinessPrice.setId(first.get().getId());
                    oilinessPrice.setUpdateTime(new Date());
                    logger.info("修改期现一体化油气价格信息参数:{}"+JSONUtil.parse(oilinessPrice));
                    int i = oilinessPriceMapper.updateById(oilinessPrice);
                    if (i == 1){
                        status = true;
                    }
                }else {
                    oilinessPrice.setCreateUser("sys");
                    oilinessPrice.setCreateTime(new Date());
                    oilinessPrice.setUpdateUser("sys");
                    oilinessPrice.setUpdateTime(new Date());
                    logger.info("保存期现一体化油气价格信息参数:{}" + JSONUtil.parse(oilinessPrice));
                    int insert = oilinessPriceMapper.insert(oilinessPrice);
                    if (insert == 1){
                        status = true;
                    }
                }
            }else {
                oilinessPrice.setId(oilinessPriceList.get(0).getId());
                oilinessPrice.setUpdateTime(new Date());
                logger.info("修改期现一体化油气价格信息参数:{}"+JSONUtil.parse(oilinessPrice));
                int i = oilinessPriceMapper.updateById(oilinessPrice);
                if (i == 1){
                    status = true;
                }
            }

        }else {
            oilinessPrice.setCreateUser("sys");
            oilinessPrice.setCreateTime(new Date());
            oilinessPrice.setUpdateUser("sys");
            oilinessPrice.setUpdateTime(new Date());
            logger.info("保存期现一体化油气价格信息参数:{}" + JSONUtil.parse(oilinessPrice));
            int insert = oilinessPriceMapper.insert(oilinessPrice);
            if (insert == 1){
                status = true;
            }
        }
        return status;
    }

    @Override
    public PageInfo<Object> querySettleOilinessPriceList(QueryOilinessPriceRq rq) {
        PageHelper.startPage(rq.getPageNum(),rq.getPageSize());
        String curveName = null;
        List<String> queryList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(rq.getCurveNameList())){
            if (rq.getCurveNameList().size() == 1){
                curveName = rq.getCurveNameList().get(0);
            }else {
                queryList = rq.getCurveNameList();
            }
        }
        String settleFwd = "F";
        List<QueryForwardOilinessInfo> returnList = new ArrayList<>();
        List<Integer> uidList = oilinessPriceMapper.queryUidList(curveName,settleFwd,queryList,rq.getStartTime(),rq.getEndTime(),null);
        PageInfo<Object> listPageInfo = new PageInfo<Object>(uidList);
        if (CollectionUtil.isNotEmpty(uidList)){
            for (Integer integer : uidList) {
                List<QueryOilinessPriceInfo> queryOilinessPriceInfoList = oilinessPriceMapper.queryOilinessPriceList(integer);
                logger.info("查询油气价格返回结果:{}"+ JSONUtil.parse(queryOilinessPriceInfoList));
                QueryForwardOilinessInfo queryForwardOilinessInfo = new QueryForwardOilinessInfo();
                if (CollectionUtil.isNotEmpty(queryOilinessPriceInfoList)){
                    List<QueryOilinessPriceInfo> list = new ArrayList<>();
                    for (int i = 0; i < queryOilinessPriceInfoList.size(); i++) {
                        if (i == 0){
                            BeanUtils.copyProperties(queryOilinessPriceInfoList.get(i),queryForwardOilinessInfo);
                        }else {
                            list.add(queryOilinessPriceInfoList.get(i));
                        }
                    }
                    queryForwardOilinessInfo.setOilinessPriceInfoList(list);
                }
                returnList.add(queryForwardOilinessInfo);
            }
        }
        PageInfo pageInfo1 = new PageInfo();
        BeanUtils.copyProperties(listPageInfo,pageInfo1);
        pageInfo1.setList(returnList);
        return pageInfo1;
    }

    @Override
    public List<QueryForwardOilinessInfo> exportOilinessPrice(ExportOilinessPriceRq rq) {
        String curveName = null;
        List<String> queryList = null;
        if (CollectionUtil.isNotEmpty(rq.getCurveNameList())){
            if (rq.getCurveNameList().size() == 1){
                curveName = rq.getCurveNameList().get(0);
            }else {
                queryList = rq.getCurveNameList();
            }
        }
        List<QueryForwardOilinessInfo> returnList = new ArrayList<>();
        if ("S".equals(rq.getSettleFwd())){
            List<QueryOilinessPriceInfo> oilinessPriceList = oilinessPriceMapper.queryOilinessList(curveName,rq.getSettleFwd(),queryList,rq.getStartTime(),rq.getEndTime(),rq.getIds());
            if (CollectionUtil.isNotEmpty(oilinessPriceList)){
                oilinessPriceList.forEach(item -> {
                    QueryForwardOilinessInfo queryForwardOilinessInfo = new QueryForwardOilinessInfo();
                    com.ship.common.core.utils.bean.BeanUtils.copyProperties(item,queryForwardOilinessInfo);
                    returnList.add(queryForwardOilinessInfo);
                });
            }
        }else if ("F".equals(rq.getSettleFwd())){
            List<Integer> uidList = oilinessPriceMapper.queryUidList(curveName,rq.getSettleFwd(),queryList,rq.getStartTime(),rq.getEndTime(),rq.getIds());
            PageInfo<Object> listPageInfo = new PageInfo<Object>(uidList);
            if (CollectionUtil.isNotEmpty(uidList)){
                for (Integer integer : uidList) {
                    List<QueryOilinessPriceInfo> queryOilinessPriceInfoList = oilinessPriceMapper.queryOilinessPriceList(integer);
                    logger.info("查询油气价格返回结果:{}"+ JSONUtil.parse(queryOilinessPriceInfoList));
//                    QueryForwardOilinessInfo queryForwardOilinessInfo = new QueryForwardOilinessInfo();
//                    if (CollectionUtil.isNotEmpty(queryOilinessPriceInfoList)){
//                        List<QueryOilinessPriceInfo> list = new ArrayList<>();
//                        for (int i = 0; i < queryOilinessPriceInfoList.size(); i++) {
//                            if (i == 0){
//                                BeanUtils.copyProperties(queryOilinessPriceInfoList.get(i),queryForwardOilinessInfo);
//                            }else {
//                                list.add(queryOilinessPriceInfoList.get(i));
//                            }
//                        }
//                        queryForwardOilinessInfo.setOilinessPriceInfoList(list);
//                    }
                    if (CollectionUtil.isNotEmpty(queryOilinessPriceInfoList)){
                        queryOilinessPriceInfoList.forEach(item -> {
                            QueryForwardOilinessInfo queryForwardOilinessInfo = new QueryForwardOilinessInfo();
                            com.ship.common.core.utils.bean.BeanUtils.copyProperties(item,queryForwardOilinessInfo);
                            returnList.add(queryForwardOilinessInfo);
                        });
                    }
                }
            }
        }
        return returnList;
    }
}
